<template>
  <!-- #ifndef H5 -->
  <view class="byt-aidialogue-tabbar byt-aidialogue-bg--float"
        :style="{ height: `calc(120rpx + env(safe-area-inset-bottom) + ${moreShow ? '100px' : '0px'})`, transition: 'all 0.2s linear' }">
    <!--  #endif -->
    <!--  #ifdef H5 -->
    <view class="byt-aidialogue-tabbar byt-aidialogue-bg--float"
          :style="{ height: `calc(160rpx + ${moreShow ? '100px' : '0px'})`, transition: 'all 0.2s linear' }">
      <!--  #endif -->

      <view class="byt-aidialogue-tabbar__box">
        <view class="byt-aidialogue-tabbar__contain">
          <view class="byt-aidialogue-tabbar__content">
            <view v-if="slotTopShow" class="byt-aidialogue-tabbar-top">
              <slot name="top"></slot>
            </view>
            <view class="byt-aidialogue-tabbar__content-input">
              <template v-if="audioShow">
                <view class="byt-aidialogue-tabbar__content-input__textarea"
                      :style="{ display: microphoneAgent ? 'flex' : 'none', borderRadius: moreShow ? '28rpx 28rpx 0 0' : '28rpx',justifyContent: 'space-between', alignItems: 'center',height: 'auto', minHeight: '92rpx'}">
                  <view v-if="quickShow" @click="quickQuestionShow = true"
                        class="byt-aidialogue-tabbar__content-input__textarea__confirm"
                        style="background-color: transparent; display: flex; justify-content: center; align-items: center;padding:16rpx 0 6rpx 24rpx;">
                    <basic-icon size="56rpx"
                                :name="colorIcon.sendLeftIcon ? colorIcon.sendLeftIcon : '/static/camera.svg'"></basic-icon>
                  </view>
                  <Audio :microphone="microphoneAgent" :message="messageAgent"
                         :startCount="startCount"></Audio>

                  <view
                      style="display: flex; flex-direction: row; align-items: center; padding-right:12rpx ;">
                    <view  style="width:80rpx; height: 88rpx;display: flex; justify-content: center; align-items: center; margin-top: 0rpx;">
                      <basic-icon size="56rpx" style="margin-top: 0rpx;"
                                  name="/static/jianpan.svg"
                                  @click="microphoneAgent = false"></basic-icon>
                    </view>

                    <block v-if="moreListShow">
                      <view style="width:80rpx; height: 88rpx;display: flex; justify-content: center; align-items: center; margin-top: 0rpx;" @click="moreShowAgent = true"
                            v-if="!moreShowAgent">
                        <basic-icon size="56rpx" style="margin-top: 0rpx;"
                                    name="/static/gengduo.svg"></basic-icon>
                      </view>
                      <view style="width:80rpx; height: 88rpx;display: flex; justify-content: center; align-items: center; margin-top: 0rpx;" @click="moreShowAgentClose"
                            v-else>
                        <basic-icon size="56rpx" style="margin-top: 0rpx;"
                                    name="/static/gengclose.svg"></basic-icon>
                      </view>
                    </block>
                  </view>
                </view>
              </template>

              <view class="byt-aidialogue-tabbar__content-input__textarea"
                    :style="{ display: !microphoneAgent ? 'flex' : 'none', alignItems: 'center', height: 'auto', minHeight: '92rpx'}">
                <view v-if="quickShow" @click="openQuick"
                      class="byt-aidialogue-tabbar__content-input__textarea__confirm"
                      style="background-color: transparent; display: flex; justify-content: center; align-items: center;padding-left: 24rpx; padding-top: 16rpx; padding-bottom: 16rpx; padding-right: 18rpx;">
                  <basic-icon size="56rpx"
                              style="display: flex; justify-content: center; align-items: center;"
                              :name="colorIcon.sendLeftIcon ? colorIcon.sendLeftIcon : '/static/camera.svg'"></basic-icon>
                </view>

                <textarea
                    class="byt-aidialogue-tabbar__content-input__textarea__inner"
                    auto-height
                    :style="{height: textareaHeight}"
                    v-model="messageAgent"
                    maxlength="-1"
                    :cursor-spacing="17"
                    placeholder=" "
                    :adjust-position="true"
                    :focus="textfocus"
                    @focus="onFocus"
                    @input="onTextareaChange"
                ></textarea>

                <view v-if="messageAgent || (!audioShow && !moreListShow)"
                      class="byt-aidialogue-tabbar__content-input__textarea__confirm "
                      :style="{ background: 'transparent', position: 'relative',marginLift:'12rpx'}">
                  <zeroLoading v-if="loading"
                               :color="colorIcon.mainColor ? colorIcon.mainColor : '#448ef7'" textGap="0rpx"
                               type="atom" position="absolute"></zeroLoading>
                  <view style="width:108rpx; height: 88rpx; display: flex; justify-content: center; align-items: center;  margin-left:12rpx;">
                    <basic-icon :style="{ opacity: messageAgent ? 1 : 0.5 }" size="56rpx"
                                style="display: flex; justify-content: center; align-items: center;"
                                :name="colorIcon.sendRightIcon ? colorIcon.sendRightIcon : 'https://img.yummall.cn/baiyetong/byt-uni-ui/sendBtn.svg'"
                                @click="setMessage"></basic-icon>
                  </view>
                </view>

                <view v-else
                      style="display: flex; flex-direction: row; align-items: center;height: 88rpx; margin-right:12rpx;">
                  <view v-if="audioShow" @click="openAudio" style="width:80rpx; height: 88rpx; display: flex; justify-content: center;align-items: center;">
                    <basic-icon size="56rpx"
                                style="display: flex; justify-content: center; align-items: center; "
                                name="/static/yuyin-2.svg"
                    ></basic-icon>
                  </view>

                  <block v-if="moreListShow">
                    <view @click="moreShowAgent = true" style="width:80rpx; height: 88rpx; display: flex; justify-content: center;align-items: center;" v-if="!moreShowAgent">
                      <basic-icon  size="56rpx"
                                   style="display: flex; justify-content: center; align-items: center;"
                                   name="/static/gengduo.svg"></basic-icon>
                    </view>

                    <view  @click="moreShowAgentClose" style="width:80rpx; height: 88rpx; display: flex; justify-content: center;align-items: center;" v-else>
                      <basic-icon size="56rpx"
                                  style="display: flex; justify-content: center; align-items: center;"
                                  name="/static/gengclose.svg"></basic-icon>
                    </view>
                  </block>
                </view>
              </view>
            </view>
          </view>

          <!-- 更多工具 -->
          <view
              :style="{ height: `calc(${moreShow ? '120px' : '0px'})`, transition: 'all 0.2s linear', overflow: 'hidden' }">
            <MoreList :items="moreList" @moreListClick="handleMoreListClick"></MoreList>
          </view>
        </view>

        <view class="safe-bottom"></view>
      </view>
      <!-- #ifndef H5 -->
    </view>
    <!--  #endif -->
    <!--  #ifdef H5 -->
  </view>
  <!--  #endif -->
</template>

<script>
import {
  getQuickQuestionList
} from '../../../common/demoMook.js';
// 图标
import BasicIcon from '../../basic/basic-icon/basic-icon.vue';
import Audio from './components/Audio/Audio.vue';
import zeroLoading from './components/zero-loading/components/zero-loading/zero-loading.vue';
import MoreList from '../MoreList/MoreList.vue';
import QuickQuestion from '../QuickQuestion/QuickQuestion.vue';
import {toBase64} from "@/js_sdk/hy-base64/hy-base64";
import {main} from "@/utils/ocr";
import {showToast} from "@/uni_modules/byt-ai-agent-uni/utils";

export default {
  components: {
    Audio,
    BasicIcon,
    zeroLoading,
    MoreList,
    QuickQuestion
  },
  name: 'Sender',
  emits: ['update:message', 'update:microphone', 'focus', 'submit' ,'ocr'],
  props: {
    // 主题色和图标
    colorIcon: {
      type: Object,
      default: () => {
        return {
          // 主题色
          mainColor: '#448ef7',
          // 辅助色
          assistColor: '#a8ecff',
          // 字体主色
          textMainColor: '#1890ff',
          // 发送框左边图标
          sendLeftIcon: '/static/camera.svg',
          // 发送框右边发送按钮
          sendRightIcon: 'https://img.yummall.cn/baiyetong/byt-uni-ui/sendBtn.svg',
          // 发送框快速提问关闭图标
          sendQuickCloseIcon: 'https://img.yummall.cn/baiyetong/byt-uni-ui/quickIconClose.svg',
          // 发送框快速提问内容左侧图标
          sendQuickContentLeftIcon: 'https://img.yummall.cn/baiyetong/byt-uni-ui/quickIcon1.svg'
        };
      }
    },
    // 是否开启语音功能
    audioShow: {
      type: Boolean,
      default: true
    },
    // 是否切换到语音输入
    microphone: {
      type: Boolean,
      default: false
    },
    // 消息内容
    message: {
      type: String,
      default: ''
    },
    // 消息回答等待loading
    loading: {
      type: Boolean,
      default: false
    },
    // 是否显示顶部插槽
    slotTopShow: {
      type: Boolean,
      default: false
    },
    // 更多工具图标按钮显示开关
    moreListShow: {
      type: Boolean,
      default: false
    },
    // 快速提问显示开关
    quickShow: {
      type: Boolean,
      default: false
    },
    // 更多组件显示
    moreShow: {
      type: Boolean,
      default: false
    },
    // 更多列表
    moreList: {
      type: Array,
      default: () => {
        return [{
          id: 1,
          icon: 'https://img.yummall.cn/baiyetong/byt-uni-ui/paishe.svg',
          name: '拍摄'
        },
          {
            id: 2,
            icon: 'https://img.yummall.cn/baiyetong/byt-uni-ui/xiangce.svg',
            name: '相册'
          },
          {
            id: 3,
            icon: 'https://img.yummall.cn/baiyetong/byt-uni-ui/luyin.svg',
            name: '录音'
          },
          {
            id: 4,
            icon: 'https://img.yummall.cn/baiyetong/byt-uni-ui/wendang.svg',
            name: '文件'
          }
        ];
      }
    }
  },
  data() {
    return {
      // 快速提问
      quickQuestionShow: false,
      // 快速提问数据
      quickQuestionList: [],
      inputOffsetBottom: 0,
      startCount: 0,
      textareaHeight: '48rpx', // 新增：文本域动态高度
      imagePath: '', // 新增：图片路径
      textfocus:false
    };
  },
  computed: {
    // 更多
    moreShowAgent: {
      get() {
        return this.moreShow;
      },
      set(val) {
        console.log(val, "jisuanshuxingfashenggaibian")
        this.$emit('update:moreShow', val);
      }
    },

    // 消息代理
    messageAgent: {
      get() {
        return this.message;
      },
      set(val) {
        this.$emit('update:message', val);
      }
    },
    // 语音和文字输入切换
    microphoneAgent: {
      get() {
        return this.microphone;
      },
      set(val) {
        this.$emit('update:microphone', val);
      }
    }
  },
  watch: {
    "moreShowAgent": {
      handle(val) {
        console.log("查看面板是否收起", val)
      }
    }
  },
  async mounted() {
    // if (this.quickShow) {
    //   // 请求快速提问数据
    //   this.getQuickList();
    // }

    // 监听语音切换
    uni.$on('updateMicrophone', (data) => {
      this.microphoneAgent = data;
    });
    // 监听消息数据变化
    uni.$on('updateMessage', (data) => {
      this.messageAgent = data;
    });
    uni.$on('textfocus', (data) => {
    });

    let _this = this;
    // 监听键盘高度变化，以便设置输入框的高度
    //  #ifndef H5
    uni.onKeyboardHeightChange((res) => {
      console.log('sender获取高度', res);
      _this.inputOffsetBottom = res.height;
      if (res.height === 0) {
        _this.focus = false;
      }
    });
    // #endif
  },
  // #ifdef VUE2
  beforeDestroy() {
    uni.$off('updateMicrophone');
    uni.$off('updateMessage');
    uni.$off('textfocus');
  },
  // #endif
  // #ifdef VUE3
  beforeUnmount() {
    uni.$off('updateMicrophone');
    uni.$off('updateMessage');
    uni.$off('textfocus');
  },
  // #endif
  methods: {
    handleMoreListClick(row) {
      if (row.id===1){
        this.moreShowAgent = false;
        this.takePhoto()
      }else {
        showToast('功能正在开发中...')
      }
    },
    moreShowAgentClose() {
      this.moreShowAgent = false;
    },
    // 获取快速提问数据
    async getQuickList() {
      this.quickQuestionList = await getQuickQuestionList();
    },
    onFocus() {
      this.$emit('focus');
    },
    quickItemClick(content) {
      this.messageAgent = content;
      this.quickQuestionShow = false;
      this.setMessage();
    },
    setMessage() {
      this.$emit('submit');
    },
    openAudio() {
      this.startCount += 1
      this.moreShowAgent = false;
    },
    openQuick(){
      this.moreShowAgent = false;
      this.takePhoto()
    },
    // 拍照功能实现
    takePhoto() {
      uni.showToast({ title: '开始图文识别...', icon: 'none',duration: 1000 });
      setTimeout(()=>{
        uni.chooseImage({
          count: 1,
          sourceType: ['camera'],
          maxWidth: 1024,
          maxHeight: 1024,
          sizeType: ['compressed'],
          success: (res) => {
            this.imagePath = res.tempFilePaths[0]
            console.log('图片路径'+this.imagePath)
            toBase64(this.imagePath).then((data) => {
              return main(data); // 返回 Promise
            }).then((ocrResult) => {
              const words_result = ocrResult.data.words_result
              let mes = ''
              words_result.forEach((item, index) => {
                mes+=item.words
              });
              console.log(mes)
              this.$emit('ocr',mes)
            }).catch((err) => {
              console.error('识别失败:', err);
              uni.showToast({ title: '识别失败', icon: 'none' });
            });
          },
          fail: (err) => {
            console.error('拍照失败:', err);
            // uni.showToast({title: '拍照失败', icon: 'none'});
          }
        });
      },1000)
    },

    // 处理选中的图片（发送图片逻辑）
    handleSelectedImage(imagePath) {
      // 显示加载状态
      this.loading = true;

      // 预览图片（可选）
      uni.previewImage({
        current: imagePath,
        urls: [imagePath]
      });

      // 发送图片给服务器（这里需要根据你的API调整）
      this.sendImageToServer(imagePath).then(() => {
        // 发送成功后重置状态
        this.loading = false;
        uni.showToast({
          title: '图片发送成功',
          icon: 'success'
        });
      }).catch((error) => {
        this.loading = false;
        console.error('发送图片失败:', error);
        uni.showToast({
          title: '图片发送失败',
          icon: 'none'
        });
      });
    },

    // 发送图片到服务器
    sendImageToServer(imagePath) {
      return new Promise((resolve, reject) => {
        // 使用uni.uploadFile上传图片
        uni.uploadFile({
          url: 'https://你的服务器API地址/upload', // 替换为实际的上传接口
          filePath: imagePath,
          name: 'file',
          success: (uploadRes) => {
            const data = JSON.parse(uploadRes.data);
            if (data.code === 200) {
              // 上传成功，获取图片URL
              const imageUrl = data.url;
              // 发送图片消息（触发父组件事件）
              this.$emit('sendImage', imageUrl);
              resolve(imageUrl);
            } else {
              reject(new Error('图片上传失败'));
            }
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },

    // 新增：监听文本域内容变化，动态调整高度
    onTextareaChange(e) {
      // 获取文本域DOM元素
      const query = uni.createSelectorQuery().in(this);
      query.select('.byt-aidialogue-tabbar__content-input__textarea__inner')
          .boundingClientRect(rect => {
            // 如果内容高度超过最小高度，更新高度
            if (rect.height > 48) { // 48rpx 转换为实际像素
              this.textareaHeight = `${rect.height}px`;
            } else {
              this.textareaHeight = '48rpx';
            }
          }).exec();
    }
  }
};
</script>

<style lang="scss" scoped>
.byt-aidialogue-tabbar__content-input__textarea {
  height: auto !important;
  min-height: 88rpx;
  display: flex;
  align-items: center;
  border-radius: 28rpx;
}

.byt-aidialogue-tabbar__content-input__textarea__inner {
  min-height: 48rpx;
  max-height: 600rpx;
  height: auto !important;
  overflow-y: auto;
  padding: 10rpx 24rpx;
  box-sizing: content-box;
  width: calc(100% - 32rpx - 80rpx);
  line-height: 48rpx;
  font-size: 28rpx;
}

/* 在 Sender.vue 的样式中添加，覆盖原有图标容器样式 */
/* camera.svg 所在容器（左侧相机图标） */
.byt-aidialogue-tabbar__content-input__textarea__confirm {
  padding: 0 24rpx !important; /* 移除上下内边距，仅保留左右 */
  height: 100% !important; /* 与父容器高度一致 */
  display: flex;
  align-items: center; /* 图标在自身容器内居中 */
}

/* jianpan.svg 所在容器（键盘图标） */
.byt-aidialogue-tabbar__content-input__textarea view:nth-child(2) > view:first-child {
  height: 100% !important; /* 与父容器高度一致（88rpx） */
  margin-top: 0 !important; /* 移除顶部margin，避免下移 */
  display: flex;
  align-items: center; /* 图标垂直居中 */
}

/* gengduo.svg 所在容器（更多图标） */
.byt-aidialogue-tabbar__content-input__textarea view:nth-child(2) > view:nth-child(2) {
  height: 100% !important; /* 与父容器高度一致 */
  margin-top: 0 !important; /* 移除顶部margin */
  display: flex;
  align-items: center; /* 图标垂直居中 */
}

/* 统一图标大小和位置，避免因图标自身尺寸导致偏移 */
basic-icon {
  margin-top: 0 !important; /* 移除图标自身的top偏移 */
}

.byt-aidialogue-tabbar {
  padding: 32rpx 32rpx;
  border-radius: 28rpx;
}

.byt-aidialogue-tabbar-top {
  width: 100%;
  height: 40px;
  position: absolute;
  z-index: 94;

  // #ifndef H5
  top: -70rpx;
  // #endif
  // #ifdef H5
  top: -70rpx;
  // #endif

  padding: 10rpx 0rpx;
  left: 34rpx;
  display: flex;
  flex-direction: row;
  gap: 16rpx;
  align-items: center;
}

view {
  box-sizing: border-box;
}

@include b(aidialogue-tabbar) {
  // #ifndef H5
  height: calc(120rpx + env(safe-area-inset-bottom));
  // #endif
  // #ifdef H5
  height: calc(160rpx);
  // #endif
  position: relative;

  @include e(box) {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 99;
    border-radius: 28rpx 28rpx;
    padding: 16rpx 32rpx 32rpx;
    box-sizing: border-box;
  }

  @include e(contain) {
    background: #fff;
    box-shadow: 0rpx 4rpx 20rpx 0rpx rgba(0, 0, 0, 0.05);
    box-sizing: border-box;
    border-radius: 28rpx 28rpx;

    @include e(content) {
      position: relative;
      max-width: 1800rpx;
      margin: 0 auto;
      padding: 10px 12px;
      box-sizing: border-box;

      @include eb(input) {
        display: flex;
        align-items: center;
        padding: 16rpx 0rpx 0rpx 0rpx;

        @include e(audio) {
          margin-right: 28rpx;
        }

        @include e(textarea) {
          flex-grow: 1;
          background-color: white;
          border-radius: 28rpx 28rpx;
          box-sizing: content-box;
          display: flex;
          justify-content: space-between;

          @include e(inner) {
            min-height: 48rpx;
            max-height: 600rpx;
            overflow-y: auto;
            padding: 10rpx 24rpx;
            box-sizing: content-box;
            width: calc(100% - 32rpx - 80rpx);
            line-height: 48rpx;
            font-size: 28rpx;
          }

          @include e(confirm) {
            flex-shrink: 0;
            width: 56rpx;
            height: 56rpx;
            background-color: #26a5ff;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
    }
  }
}
</style>